import 'dart:io';

import 'package:flutter/material.dart';
import 'package:getwidget/components/image/gf_image_overlay.dart';
import 'package:images_picker/images_picker.dart';
import 'package:meal/constant/sizes.dart';
import 'package:meal/utils/colors.dart';
import 'package:meal/utils/tools.dart';

typedef SelectedImage = void Function(List<Media> res);

///
/// 上传图片或者手机拍照
///
class MyUpload extends StatefulWidget {
  final SelectedImage? gallery;
  final SelectedImage? camera;
  final EdgeInsets? margin;
  final int count;

  /// 上传图片
  final List<String> uploads;

  /// 删除
  final ValueChanged<String>? deleteUpload;

  final Alignment? alignment;

  const MyUpload(
      {Key? key,
      this.gallery,
      this.camera,
      this.margin,
      this.count = 10,
      this.uploads = const [],
      this.deleteUpload,
      this.alignment})
      : super(key: key);

  @override
  State<MyUpload> createState() => _MyUploadState();
}

class _MyUploadState extends State<MyUpload> {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: widget.margin,
      alignment: widget.alignment ?? Alignment.center,
      child: Wrap(
        alignment: WrapAlignment.center,
        runAlignment: WrapAlignment.center,
        crossAxisAlignment: WrapCrossAlignment.center,
        spacing: Sizes.default10,
        runSpacing: Sizes.default10,
        children: [
          ...widget.uploads.map((e) {
            return InkWell(
              onTap: () {
                widget.deleteUpload!.call(e);
              },
              child: Stack(
                children: [
                  GFImageOverlay(
                      height: Sizes.default80, width: Sizes.default80, image: FileImage(File(e))),
                  Positioned(
                      top: 0,
                      right: 0,
                      width: 20,
                      height: 20,
                      child: Icon(Icons.delete,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorFa5),
                          size: Sizes.default20))
                ],
              ),
            );
          }).toList(),
          upload(),
        ],
      ),
    );
  }

  Widget upload() {
    return InkWell(
      onTap: () {
        ToolsUtils.openGalleryOrCamera(context, widget.gallery, widget.camera, widget.count);
      },
      child: Container(
        constraints: const BoxConstraints.tightFor(
          height: Sizes.default80,
          width: Sizes.default80,
        ),
        color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorB2b),
        alignment: Alignment.center,
        child: Icon(Icons.add_a_photo_rounded,
            size: Sizes.default28,
            color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorWhite)),
      ),
    );
  }
}
